package com.diadraw.extensions.mail
{
	import flash.events.DataEvent;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.events.StatusEvent;
	import flash.external.ExtensionContext;
	
	
	/**
	 * An iOS native extension for Adobe AIR 3.1 for sending mail.
	 * Implements MFMailComposeViewController in iOS
	 * Based on the example by Piotr Kościerzyński, 
	 * http://flashsimulations.com/2011/11/30/ios-native-extension-for-adobe-air-in-app-mail-composer/
	 * 
	 * */
	
	public class NativeMailWrapper extends EventDispatcher
	{
		public static const EXT_EVENT : String = "EXT_EVENT";
		
		
		public function NativeMailWrapper( target : IEventDispatcher = null )
		{
			super( target );
		}
		
		
		public function isMailComposerAvailable() : Boolean
		{
			ensureContext();
			
			return ( null == m_extensionContext ) ? false : m_extensionContext.call( "as_isEmailConfigured") as Boolean;			
		}
		

		public function dispose() : void 
		{
			m_extensionContext.removeEventListener( StatusEvent.STATUS, onStatusEvent );
			m_extensionContext.dispose();
		}	
		
		
		private function ensureContext() : void	
		{
			if ( null != m_extensionContext )
			{
				dispatchEvent( new DataEvent( EXT_EVENT, false, false, "Context already initialised" ) );
				return;
			}			
			
			m_extensionContext = ExtensionContext.createExtensionContext( EXTENSION_ID, null);
			
			try
			{
				m_extensionContext = ExtensionContext.createExtensionContext( EXTENSION_ID, null );
			}
			catch ( error : ArgumentError )
			{
				dispatchEvent( new DataEvent( EXT_EVENT, false, false, "Error: " + error.toString() ) );
			}
		}
		
		
		public function sendMail( subject 			: String = "", 
								  messageBody		: String = "", 
								  toRecipients		: String = "",
								  ccRecipients		: String = "", 
								  bccRecipients		: String = "", 
								  attachmentsData	: Array  = null,
								  useHtml			: Boolean = true ):void 
		{
			ensureContext();
			
			if ( null != m_extensionContext )
			{
				m_extensionContext.removeEventListener( StatusEvent.STATUS, onStatusEvent);
				m_extensionContext.addEventListener( StatusEvent.STATUS, onStatusEvent);
				
				m_extensionContext.call( 
					"as_sendEmail", 
					subject, 
					messageBody, 
					toRecipients,
					ccRecipients, 
					bccRecipients, 
					attachmentsData,
					useHtml );
			}
		}
		
		
		private function onStatusEvent( event : StatusEvent ) : void
		{
			dispatchEvent( new MailExtensionEvent( event.code, event.level ) );
		}
		
		
		private static const EXTENSION_ID : String = "com.diadraw.extensions.email.NativeEmailLauncher";
		private var m_extensionContext : ExtensionContext;		
	}
}